package middleware

import (
	"net/http"
	"strconv"

	// "GinAdmin/internal/model"
	// "GinAdmin/pkg/auth"
	"GinAdmin/core/auth"
	"GinAdmin/model"

	"github.com/gin-gonic/gin"
)

// Casbin 权限中间件
func Casbin() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 获取当前用户
		userID, exists := c.Get("userID")
		if !exists {
			c.JSON(http.StatusUnauthorized, model.Response{
				Code: http.StatusUnauthorized,
				Msg:  "未授权",
			})
			c.Abort()
			return
		}

		// 将用户ID转为字符串
		sub := strconv.FormatUint(uint64(userID.(uint)), 10)
		// 请求的路径
		obj := c.Request.URL.Path
		// 请求的方法
		act := c.Request.Method

		// 检查权限
		allowed, err := auth.CheckPermission(sub, obj, act)
		if err != nil {
			c.JSON(http.StatusInternalServerError, model.Response{
				Code: http.StatusInternalServerError,
				Msg:  "权限检查错误: " + err.Error(),
			})
			c.Abort()
			return
		}

		if !allowed {
			c.JSON(http.StatusForbidden, model.Response{
				Code: http.StatusForbidden,
				Msg:  "没有访问权限",
			})
			c.Abort()
			return
		}

		c.Next()
	}
}
